import { ShElement } from './ShElement'


export class ShTab extends ShElement {
    
    constructor() {
        super()

        this.$shadow.innerHTML = `
            <style> 
                :host {
                    padding: 0 2em;
                    background-color: white;
                    display: flex;
                    cursor: pointer;
                    justify-content: center;
                    align-items: center;
                }
            </style>
            <slot></slot>
        `
    }

    public get name(): string {
        return this.getAttribute('name') || ''
    }
}
customElements.define('sh-tab', ShTab)


export class ShTabbar extends ShElement {

    private $activeTab: ShTab | null = null

    constructor() {
        super()

        this.$shadow.innerHTML = `
            <style>
                :host {
                    height: 2.5em;
                    border-bottom: solid 2px var(--color-primary);
                    display: flex;
                    justify-content: center;
                }
            </style>
            <slot></slot>
        `
    }

    connectedCallback() {
        for (let i = 0; i < this.children.length; i++) {
            const $tab = this.children[i] as ShTab
            if ($tab.tagName !== 'SH-TAB')
                continue
            
            if ($tab.hasClass('sh-selected')) {
                this.$activeTab = $tab
                this.dispatchEvent(new CustomEvent('shev-select', { detail: $tab.name }))
            }

            $tab.on('pointerdown', () => {
                this.$activeTab?.removeClass('sh-selected')
                $tab.addClass('sh-selected')
                this.$activeTab = $tab
                this.dispatchEvent(new CustomEvent('shev-select', { detail: $tab.name }))
            })
        }
    }
}
customElements.define('sh-tabbar', ShTabbar)
